window.AppContext = ( function() {
	//xuejianxin @20200519
	function fetchAndParse( URL ,customOptions) {
		return fetch( URL ).then( ( response ) => {
			return response.text();
		} ).then( ( html ) => {
			const parser = new DOMParser();
			const document = parser.parseFromString( html, 'text/html' );
			const head = document.head;
			const template = head.querySelector( 'template' );
			const style = head.querySelector( 'style' );
			const script = head.querySelector( 'script' );
			return {
				template,
				style,
				script,
				customOptions
			};
		} );
	}

	
	function getSettings( { template, style, script ,customOptions } ) {
		const jsFile = new Blob( [ script.textContent ], { type: 'application/javascript' } );
		const jsURL = URL.createObjectURL( jsFile );
		const compId="comp-"+(jsURL.substring(jsURL.lastIndexOf("/")+1));
		return import( jsURL ).then( ( module ) => {//import动态引入js
			module.default._id=compId;
			module.default.mixins= [customOptions];//vue混入
			var config;
			if(style){
                registerComponent({defaultOptions: module.default, template, style });
                var html=["<",compId,">","</",compId,">"].join('');
			    config= {template:  html };
			}else{
				module.default.template=template
				config=module.default;
			}
			return config;
		} );
	}
	
	function registerComponent( {defaultOptions, template, style } ) {
		class UnityComponent extends HTMLElement {
			connectedCallback() {
				this._attachShadow();
			    this._createVue();
			}
			_attachShadow() {
				const shadow = this.attachShadow( { mode: 'open' } );
				shadow.appendChild( document.importNode( template.content, true ) );
				shadow.appendChild( style.cloneNode( true ) );
			}
			_createVue(){
				var root=this.shadowRoot;
				defaultOptions.el=root.querySelector(':first-child');
				new Vue(defaultOptions);
			}
			
		}

		
		return customElements.define(defaultOptions._id, UnityComponent );
	}
  
	function loadComponentAsyn (url,customOptions) {
		 return function(){
			         /*function lastOp (defaultOptions){
			        	 return new Promise (function (resolve, reject){
			        		 resolve( defaultOptions);
			             }); 
			             
			             //.then(lastOp)
			         }*/
			         customOptions=customOptions||{};
				     return  {
				         component: fetchAndParse(url+"?t="+(new Date().getTime()), customOptions ).then(getSettings)
				        ,loading  : {template: '<p>loading...</p>'}
				        ,error    : {template: '<p style="color:red;">load failed!</p>'}
				        ,delay    : 10
				        ,timeout  : 3200
				    };
		}
   }
	
	
   function loadComponent (url,customOptions /*自定义选项*/){
 	  return (loadComponentAsyn(url,customOptions))();
   }
	
   function createComponent (tagName,templateUrl,dialogOptions){
   	 return Vue.component(tagName,()=>loadComponent(templateUrl,dialogOptions));
   }
	
	
	
	
	
	return {loadComponentAsyn,loadComponent};
	
}() );
